package com.ylz.sjzx.sio.room.adapter;

/*
 * 账号绑定实现
 *注意:这里socket 握手并未完全
 */

import cn.hutool.core.util.StrUtil;
import com.ylz.sjzx.sio.common.core.constant.IMConstant;
import com.ylz.sjzx.sio.common.core.enums.Cmd;
import com.ylz.sjzx.sio.room.entity.LoginDelayItem;
import com.ylz.sjzx.sio.common.core.core.container.common.annotation.AdapterDesc;
import com.ylz.sjzx.sio.sdk.client.core.AbstractBaseAdapter;
import com.ylz.sjzx.sio.sdk.client.service.IMSessionService;
import com.ylz.sjzx.sio.sdk.client.session.IMSession;
import com.ylz.sjzx.sio.sdk.client.session.UserSession;
import com.ylz.sjzx.sio.sdk.client.utils.SessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 注意:这里socket 握手并未完全
 */
@Component
@AdapterDesc(id = IMConstant.LOGIN_KEY)
public class LoginAdapter extends AbstractBaseAdapter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private Object obj = new Object();

    @Autowired
    private IMSessionService cimSessionService;


    @Override
    public void process() {

        //并发登录会导致这边用户同时插入到session 暂不加锁 socketIo 有做锁 ws 没有
        IMSession newSession = this.getSession();
        UserSession userSession = SessionUtil.getUserSessionService().getOrAddByUserId(newSession.getUserId());
        logger.info("====sid={},uid={},===loginIn加锁===", newSession.getSid(), newSession.getUserId());
        if (!userSession.lockLogin()) {
            //如果失败 那么物理断开的登录逻辑也不会处理
            logger.info("====sid={},uid={},===loginIn加锁失败,结束===", newSession.getSid(), newSession.getUserId());
            return;
        }
        if (this.precheck(newSession)) {
            //前置登录检查
            userSession.unLockLogin();
            logger.info("====sid={},uid={},===loginIn释放锁===", newSession.getSid(), newSession.getUserId());
            return;
        }
        //聊天室存在 获取对应的聊天室
        if (Objects.equals("pc", newSession.getDeviceType()) && StrUtil.isNotBlank(newSession.getRoomName())) {
            LoginDelayItem loginDelayItem = new LoginDelayItem(Cmd.login, newSession.getSid(), 350L, null);
            LoginAfterService.add(loginDelayItem);
        } else {
            LoginDelayItem loginDelayItem = new LoginDelayItem(Cmd.login, newSession.getSid(), 450L, null);
            LoginAfterService.add(loginDelayItem);
        }

    }

    /**
     * 前置登录检查
     *
     * @param newSession
     */
    private Boolean precheck(IMSession newSession) {
        Boolean flag = false;
        IMSession oldSession = null;
        try {
            oldSession = this.cimSessionService.getByUserId(newSession.getRoomName(), newSession.getUserId());
        } catch (Exception e) {
            logger.error("请求上次的登录用户信息失败:{}", newSession, e);

        }
        //因为集群的关系有可能oldSession是在别的机器所以只判断redis中是否有session缓存
        if (oldSession == null) {
            return flag;
        }
        //多端登录处理
        this.cimSessionService.saveTemp(newSession);
        return false;
    }

}
